import Taro, { getCurrentInstance } from '@tarojs/taro';
import { useState, useEffect } from "react";
import { View } from '@tarojs/components';
import { AtButton, AtToast } from 'taro-ui';
import { createActivity } from "@/api/application/volunteer";
import Header from '@/components/header';
import Return from '@/components/Return';
import PreContent from '@/components/PreContent/index.jsx';
import SubmitOkModal from '@/components/SubmitOkModal';
import "taro-ui/dist/style/components/toast.scss";
import css from './index.module.less';

export default function PreviewActivity() {
  const router = getCurrentInstance().router.params;
  const formData = JSON.parse(decodeURIComponent(router.data));
  const { name, organizationName,
    activityContact, activityContent,
    activityLocation, activitySponsorId,
    activityTime, activityTitle,
    contactNumber, meetingPlace,
    registrationDeadline, imgs, files } = formData;
  //上传文件相关数据
  const [imgIds, setImgIds] = useState([]);
  const [fileIds, setFileIds] = useState([]);
  //提交成功弹窗的可见性
  const [submitOkVis, setSubmitOkVis] = useState(false);
  //加载中
  const [isOpened, setIsOpened] = useState(false);
  //是否提交
  const [isSubmit, setIsSubmit] = useState(false);

  const data = {
    bigTitle: "预览活动",
    title: activityTitle,
    name,
    organizationName,
    content: activityContent,
    activityContact,
    contactNumber,
    activityLocation,
    meetingPlace,
    activityTime,
    registrationDeadline,
    imgs, files
  };

  useEffect(() => {
    if (isSubmit) {
      if (imgs.length > 0) {
        if (imgIds.length < imgs.length) {
          uploadImgFiles(imgIds.length);
        }
        else if (imgIds.length === imgs.length) uploadExtraFiles(0);
      }
    }
  }, [imgIds]);
  useEffect(() => {
    if (isSubmit) {
      if (files.length > 0) {
        if (fileIds.length < files.length) {
          uploadExtraFiles(fileIds.length);
        }
        else if (fileIds.length === files.length) create();
      }
    }
  }, [fileIds]);

  function uploadImgFiles(index) {
    if (imgs.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/service_volunteer_activity/0/img',
        filePath: imgs[index].url,
        name: "file",
        success: function (resImg) {
          imgIds.push(JSON.parse(resImg.data).data.id);
          setImgIds([...imgIds]);
        },
      });
    }
    else uploadExtraFiles(0);
  }

  function uploadExtraFiles(index) {
    if (files.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/service_volunteer_activity/0/file',
        filePath: files[index].path,
        name: "file",
        success: function (resExtra) {
          fileIds.push(JSON.parse(resExtra.data).data.id);
          setFileIds([...fileIds]);
        },
      });
    }
    else create();
  }

  const create = () => {
    const info = {
      activityContact, activityContent,
      activityLocation, activitySponsorId,
      activityTime, activityTitle,
      contactNumber, meetingPlace,
      registrationDeadline, imgIds, fileIds,
    };
    createActivity(info).then(res => {
      if (res.code === 200) {
        setSubmitOkVis(true);
      }
    }).finally(() => { setIsOpened(false); });
  };

  const onSubmit = () => {
    setIsSubmit(true);
    setIsOpened(true);
    uploadImgFiles(0);
  };

  return (
    <View className={css.home}>
      <Header message='预览活动' left='140px' />
      <Return />
      <View className={css.articleCon}>
        <PreContent data={data} />
        <View className={css.buttonBox}>
          <AtButton className={css.submitButton} circle onClick={onSubmit}>提交</AtButton>
        </View>
      </View>

      <SubmitOkModal
        visible={submitOkVis}
        setVisible={setSubmitOkVis}
        url='../../../index'
        text='志愿活动'
      />

      <AtToast isOpened={isOpened} text='上传数据中...' status='loading' duration={0} hasMask />
    </View>
  );
}